/*
 * ChatPanel.java
 *
 * Created on September 23, 2008, 10:24 PM
 */
package no.eirikb.bomberman.applet.chat;

import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import no.eirikb.bomberman.applet.Bomberman;
import no.eirikb.bomberman.server.Server;
import no.eirikb.bomberman.shared.message.Message;
import no.eirikb.bomberman.shared.User;
import no.eirikb.bomberman.shared.message.PrivateMessage;
import no.eirikb.bomberman.shared.message.PublicMessage;

/**
 *
 * @author  eirikb
 */
public class ChatPanel extends javax.swing.JPanel {

    private Bomberman bomberman;
    private String to;
    private final String help = "Welcome to bomberman!";

    private enum Commands {

        M, MSG, UNKNOWN, HELP;

        public static Commands getCommand(String cmd) {
            try {
                return Commands.valueOf(cmd.toUpperCase());
            } catch (IllegalArgumentException e) {
                return UNKNOWN;
            }
        }
    }

    /** Creates new form ChatPanel */
    public ChatPanel(Bomberman bomberman, String to) {
        this.bomberman = bomberman;
        this.to = to;
        initComponents();
    }

    public void chat(Message message) {
        if (message.getFrom() != null) {
            chatArea.append("\n<" + message.getFrom() + "> " + message.getMessage());
        } else {
            chatArea.append("\n" + message.getMessage());
        }
        chatArea.setCaretPosition(chatArea.getText().length());
    }

    private void command(String line) {
        Commands cmd;
        if (line.indexOf(" ") >= 0) {
            cmd = Commands.getCommand(line.substring(0, line.indexOf(" ")));
            line = line.substring(line.indexOf(" ") + 1);
        } else {
            cmd = Commands.getCommand(line);
            line = null;
        }
        switch (cmd) {
            case HELP:
                chatArea.append("\n" + help + "\nCommands:");
                for (Commands c : Commands.values()) {
                    if (c != Commands.UNKNOWN) {
                        chatArea.append("\n" + c);
                    }
                }
                break;
            case MSG:
            case M:
                if (line != null && line.indexOf(" ") > 0) {
                    String msg = line.substring(line.indexOf(" ") + 1);
                    line = line.substring(0, line.indexOf(" "));
                    try {
                        if (bomberman.getServer().chat(bomberman.getHash(),
                                new PrivateMessage(bomberman.getUser().getNick(), line, msg))) {
                            chatArea.append("\n* Message sent!");
                        } else {
                            chatArea.append("\nMessage was recieved by server, but dropped");
                            chatArea.append("\nUnknown user?");
                        }
                    } catch (RemoteException ex) {
                        Logger.getLogger(ChatPanel.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                break;
            case UNKNOWN:
                chatArea.append("\nUnknown command");
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        chatScrollPane = new javax.swing.JScrollPane();
        chatArea = new javax.swing.JTextArea();
        chatField = new javax.swing.JTextField();

        chatScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        chatArea.setColumns(20);
        chatArea.setLineWrap(true);
        chatArea.setRows(5);
        chatArea.setWrapStyleWord(true);
        chatScrollPane.setViewportView(chatArea);

        chatField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chatFieldActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 536, Short.MAX_VALUE)
            .addComponent(chatField, javax.swing.GroupLayout.DEFAULT_SIZE, 536, Short.MAX_VALUE)
            .addComponent(chatScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 536, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 268, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(chatScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(chatField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void chatFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chatFieldActionPerformed
    String line;
    if ((line = chatField.getText()).length() > 0) {
        if (line.charAt(0) == '/') {
            line = line.substring(1);
            command(line);
        } else {
            try {
                if (to == null) {
                    if (!bomberman.getServer().chat(bomberman.getHash(),
                            new PublicMessage(bomberman.getUser().getNick(), line))) {
                        chatArea.append("\nMessage was recieved by server, but dropped");
                    }
                } else {
                    if (!bomberman.getServer().chat(bomberman.getHash(),
                            new PrivateMessage(bomberman.getUser().getNick(), to, line))) {
                        chatArea.append("\nMessage was recieved by server, but dropped");
                        chatArea.append("\nUnknown user?");
                    } else {
                        chatArea.append("\n<" + bomberman.getUser().getNick() + "> " + line);
                    }
                }

            } catch (RemoteException ex) {
                Logger.getLogger(ChatContainerPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        chatField.setText("");
    }
}//GEN-LAST:event_chatFieldActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea chatArea;
    private javax.swing.JTextField chatField;
    private javax.swing.JScrollPane chatScrollPane;
    // End of variables declaration//GEN-END:variables
}
